#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include "GCore.h"
#include "GWindow.h"
#include "GMessageHandler.h"
#include "GMessageManager.h"
#include "GError.h"
#include "GApplication.h"

namespace GEngine
{
	bool GMessageManager::Update() PLATFORM
	{
		MSG Msg;

		// Collect messages for each window
		GSize WindowCount = mGAppModule->GetWindowCount();
		for (GSize I = 0; I < WindowCount; ++I)
		{			
			memset(&Msg, 0, sizeof(MSG));

			// Get messages for this window if there are any
			GWindow* Window = mGAppModule->GetWindowByIndex(I);
			HWND WindowHandle = static_cast<HWND>(Window->GetHandle());

			// PostQuitMessage is called peek message will return 0
			while (PeekMessage(&Msg, WindowHandle, 0, 0, PM_REMOVE) != 0)
			{
				TranslateMessage(&Msg);

				// Send the message to appropiate window procedure
				// Messages will be queued in this class
				DispatchMessage(&Msg);
			}

			//! call peekmessage with -1 HWND and check which thread messages arrive.
			//! process thread messages if possible
		}

		// Dispatch the collected messages of windows
		DispatchMessages();

		return true;
	}

	GUInt32 GMessageManager::RegisterMessage(const char* MsgStr) PLATFORM
	{
		GUInt32 Result = RegisterWindowMessage(MsgStr);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return 0;
		}

		return Result;
	}
}
